/* eslint-disable @typescript-eslint/no-shadow */
/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\bookManage\index.tsx
 * @Description  : 图书管理页面
 */

import { PageContainer } from '@ant-design/pro-layout';
import React, { useRef, useState } from 'react';
import { Badge, Button, message, Popconfirm, Space } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import CreateBook from './booksComponents/CreateBook';
import EditBook from './booksComponents/EditBook';
import DamageBook from './booksComponents/DamageBook';
import type { ParamsType } from '@ant-design/pro-provider';
import { deleteBook, getBookList, getBookTypeList } from '@/services/books';
import styles from './index.less';
import type { BookList } from '@/dataType';

/**
 * 图书管理页面，渲染图书列表，引用子级组件实现功能
 * @returns
 */
function BookManage() {
  const actionRef = useRef<ActionType>();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false);
  const [isModalVisibleDamage, setIsModalVisibleDamage] = useState(false);
  const [bookAid, setBookAid] = useState(undefined);
  const [show, setShow] = React.useState(true);
  const [bookNum, setBookNum] = React.useState(Number);

  /**
   * 新增模态框的控制
   */
  const isShowModal = (show: boolean | ((prevState: boolean) => boolean)) => {
    setIsModalVisible(show);
  };

  /**
   * 修改模态框的控制
   */
  const isShowModalEdit = (show: boolean | ((prevState: boolean) => boolean), aid: any) => {
    setBookAid(aid);
    setIsModalVisibleEdit(show);
  };

  /**
   * 报损模态框的控制
   */
  const isShowModalDamage = (show: boolean | ((prevState: boolean) => boolean), aid: any) => {
    setBookAid(aid);
    setIsModalVisibleDamage(show);
  };

  /**
   * 获取图书列表数据
   * @param params
   * @returns
   */
  const getBooksData = async (
    params: ParamsType & {
      pageSize?: number | undefined;
      current?: number | undefined;
      keyword?: string | undefined;
    },
  ) => {
    const param = {
      searchKey: params.searchKey,
      typeAid: params.typeAid,
      page: params.current!,
      pageSize: params.pageSize!,
    };
    const response = await getBookList(param);
    setBookNum(response.bookNum);
    setShow(true);
    return {
      data: response.list,
      success: true,
      total: response.rowsNum,
    };
  };

  /**
   * 删除用户按钮确认提示
   * @param params
   */
  const confirm = async (aid: number) => {
    const params = {
      aid: aid,
    };
    const response = await deleteBook(params);
    if (response) {
      message.success('删除成功！');
      actionRef.current?.reload();
    }
  };
  function cancel() {
    message.error('取消删除！');
  }

  /**
   * 表格的设计
   */
  const columns: ProColumns<BookList>[] = [
    {
      title: 'ISBN号',
      width: 160,
      dataIndex: 'isbn',
      hideInSearch: true,
    },
    {
      title: '类型',
      width: 157,
      dataIndex: 'typeName',
      filters: true,
      onFilter: true,
      hideInSearch: true,
    },
    {
      title: '图书名称',
      width: 254,
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '图书名称',
      width: 254,
      dataIndex: 'searchKey',
      copyable: true,
      ellipsis: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '类型',
      dataIndex: 'typeName',
      key: 'typeAid',
      filters: true,
      onFilter: true,
      valueType: 'select',
      hideInTable: true,
      request: async () => {
        const data = await getBookTypeList();
        return data.map((item) => {
          return {
            label: item.name,
            value: item.aid,
          };
        });
      },
    },
    {
      title: '数量',
      width: 100,
      dataIndex: 'quantity',
      hideInSearch: true,
    },
    {
      title: '新增时间',
      width: 183,
      key: 'showTime',
      dataIndex: 'createDate',
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '操作',
      width: 282,
      hideInSearch: true,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            className={styles.button}
            onClick={() => {
              isShowModalEdit(true, record.aid);
            }}
          >
            修改
          </Button>
          <Popconfirm
            placement="topRight"
            title="你确认要删除该项数据吗??"
            onConfirm={() => confirm(record.aid)}
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <Button type="link" className={styles.button}>
              删除
            </Button>
          </Popconfirm>
          <Button
            type="link"
            className={styles.button}
            onClick={() => {
              isShowModalDamage(true, record.aid);
            }}
          >
            报损
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '图书管理',
        ghost: true,
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织构架',
            },
            {
              path: '',
              breadcrumbName: '图书管理',
            },
          ],
        },
      }}
    >
      <ProTable<BookList>
        columns={columns}
        actionRef={actionRef}
        request={(params) => getBooksData(params)}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          span: 6,
        }}
        options={{
          density: false,
          setting: false,
          fullScreen: true,
        }}
        pagination={{
          pageSize: 10,
          size: 'default',
          showTotal: undefined,
        }}
        dateFormatter="string"
        headerTitle={
          <div>
            <span>图书列表</span>
            <Badge
              count={show ? bookNum : 0}
              overflowCount={10000000}
              style={{ marginLeft: '10px', color: '#1890ff', backgroundColor: '#e6f7ff' }}
            />
            <span className={styles.bookNum}>图书总量</span>
          </div>
        }
        toolBarRender={() => [
          <Button key="button" type="primary" onClick={() => isShowModal(true)}>
            新增
          </Button>,
        ]}
      />

      {/* 引用新增图书模块 */}
      <CreateBook isModalVisible={isModalVisible} isShowModal={isShowModal} actionRef={actionRef} />

      {/* 引用修改图书模块 */}
      <EditBook
        isModalVisible={isModalVisibleEdit}
        isShowModal={isShowModalEdit}
        actionRef={actionRef}
        bookAid={bookAid}
      />

      {/* 引用图书报损模块 */}
      <DamageBook
        isModalVisible={isModalVisibleDamage}
        isShowModal={isShowModalDamage}
        actionRef={actionRef}
        bookAid={bookAid}
      />
    </PageContainer>
  );
}
export default BookManage;
